<?php
# http://projects:8081/cdapp-2kt-api/api/activity_military_load.php
include_once './_portal.php';
include_once './request_sipds.php';

const MIN_TTL    = 10 * 1000;
const MAX_TTL    = 20 * 1000;
const PARAM_NAME = 'activityMilitaryRefreshTime';
const API_NAME   = 'milAvtnPlanWebService.findMilAvtnPlanPage';
const DEF_UNITS  = ['温江', '邛崃', '太平寺', '夹江', '彭州', '中江', '广汉', '新津', '遂宁', '绵阳', '大足', '白市驿', '泸州', '宜宾', '五粮液', '宜宾五粮液'];

$refresh_info = get_param(PARAM_NAME);
$ttl_verify   = verify_ttl($refresh_info['tx'], $refresh_info['rx'], MIN_TTL, MAX_TTL);
$info         = 'activity_military_load: ' . $ttl_verify['info'];
$status       = $ttl_verify['status'];
$time         = $ttl_verify['time'];

if ($status > 0) {
  save_param(PARAM_NAME, ['tx' => $time, 'rx' => $refresh_info['rx']]);
  $request_result = refresh_data(API_NAME);
  $info .= ' ' . $request_result['info'];
  $status  = $status * $request_result['status'];
  $time_rx = timestamp();
  save_param(PARAM_NAME, ['tx' => $time, 'rx' => $time_rx]);
}

output([
  'status' => $status,
  'info'   => $info,
  'data'   => exec_sql("SELECT * FROM `2kt_activity_military`"),
]);

die();

# request content from sipds
function refresh_data($api_name) {
  $response  = request_sipds($api_name);
  $sql_clean = "TRUNCATE TABLE `2kt_activity_military`";
  $result    = true;
  $sql_arr   = [$sql_clean];
  if ($response['status'] == 0) {
    return [
      'status' => 0,
      'info'   => 'Failed to refresh data, sending request failed.',
    ];
  }
  if (! isset($response['data']['CONTENTS']) || $response['data']['CONTENTS'] == null) {
    // return [
    //   'status' => 0,
    //   'info' => 'Failed to refresh data, recived null response.',
    // ];
  } else {
    $concerned_unit_list = init_param('CONCERNED_UNIT_LIST', DEF_UNITS);
    $sql                 = "INSERT INTO `2kt_activity_military` (`number`, `name`, `unit`, `arrField`, `depField`, `date`, `fullATD`, `ATD`, `ETA`, `ETD`, `route`, `remark`) VALUES ";
    foreach ($response['data']['CONTENTS'] as $res) {
      $element = [
        'name'     => escape_string(truncate_chars($res['FLTID'] ?? '')),
        'unit'     => escape_string(truncate_chars($res['UNIT'] ?? '')),
        'arrField' => escape_string($res['ARRAP'] ?? ''),
        'depField' => escape_string($res['DEPAP'] ?? ''),
        'date'     => substr($res['WHICHDAY'], 0, 10) . ' ' . substr($res['WHICHDAY'], 11, 8),
        'fullATD'  => substr($res['ATD'], 0, 10) . ' ' . substr($res['ATD'], 11, 8),
        'ATD'      => $res['ATTRI2'] ?? '',
        'ETA'      => $res['ETA'] ?? '',
        'ETD'      => $res['ETD'] ?? '',
        'route'    => escape_string($res['ROUTE'] ?? ''),
        'remark'   => ($res['USERMEMO'] ?? '') . ($res['HEIGHT'] ?? ''),
      ];
      // added unit check to prevent illegal words @2025-04-23
      if (
        in_array($element['unit'], $concerned_unit_list) ||
        in_array($element['arrField'], $concerned_unit_list) ||
        in_array($element['depField'], $concerned_unit_list)
      ) {
        $sql .= "(null, '{$element['name']}', '{$element['unit']}', '{$element['arrField']}', '{$element['depField']}', '{$element['date']}', '{$element['fullATD']}', '{$element['ATD']}', '{$element['ETA']}', '{$element['ETD']}', '{$element['route']}', '{$element['remark']}'),";
      }
    }
    $sql = rtrim($sql, ',');
    array_push($sql_arr, $sql);
  }
  $result_arr = exec_sql_array($sql_arr);
  foreach ($result_arr as $r) {
    $result = $result && $r;
  }

  // added history record function @2024/08/29
  $result_history = update_activity_history();
  if ($result) {
    return [
      'status'  => 1,
      'info'    => 'Successed to refresh data.',
      'history' => $result_history,
    ];
  } else {
    return [
      'status'  => 0,
      'info'    => 'Failed refresh data, database update filed.',
      'history' => $result_history,
    ];
  }
}

function update_activity_history() {
  // added history record function @2024/08/29
  // modified @2025/7/26

  // 新建记录表
  exec_sql("CREATE TABLE IF NOT EXISTS `cdapp`.`2kt_activity_history` (`number` INT(8) NOT NULL AUTO_INCREMENT , `unit` TEXT NOT NULL , `callsign` TEXT NOT NULL , `category` VARCHAR(4) NOT NULL , `startTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP , `endTime` DATETIME NULL DEFAULT NULL , `flightCount` INT(5) NOT NULL DEFAULT '0' , PRIMARY KEY (`number`)) ENGINE = InnoDB");

  $sql         = "SELECT * FROM `2kt_activity_military`";
  $current_rec = exec_sql($sql);

  $sql         = "SELECT * FROM `2kt_activity_history` WHERE `endTime` IS NULL AND `category` = 'M'";
  $existed_rec = exec_sql($sql);

  if (! $current_rec || ! is_array($current_rec)) {
    $current_rec = [];
  }

  if (! $existed_rec || ! is_array($existed_rec)) {
    $existed_rec = [];
  }

  $concerned_unit_list = init_param('CONCERNED_UNIT_LIST', DEF_UNITS);

  $current_rec_units = [];

  foreach ($current_rec as $rec) {
    $unit     = $rec['unit'];
    $arrField = $rec['arrField'];
    $depField = $rec['depField'];

    if (in_array($unit, $concerned_unit_list, true) && ! in_array($unit, $current_rec_units, true)) {
      $current_rec_units[] = $unit;
    }

    if (in_array($arrField, $concerned_unit_list, true) && ! in_array($arrField, $current_rec_units, true)) {
      $current_rec_units[] = $arrField;
    }

    if (in_array($depField, $concerned_unit_list, true) && ! in_array($depField, $current_rec_units, true)) {
      $current_rec_units[] = $depField;
    }
  }

  $need_to_add = [];
  $need_to_end = [];

  $need_to_add_units = [];
  $need_to_end_units = [];

  $now_time = date('Y-m-d H:i:s');
  $now_date = date('Y-M-D');

  // 需要添加的活动记录
  foreach ($current_rec_units as $unit) {
    $is_existed = false;
    foreach ($existed_rec as $rec) {
      if ($rec['unit'] == $unit) {
        $is_existed = true;
        break;
      }
    }
    if (! $is_existed) {
      $need_to_add_units[] = $unit;
      $need_to_add[]       = "INSERT INTO `2kt_activity_history` (`unit`,`callsign`,`category`,`startTime`) VALUES ('{$unit}','{$unit}','M','{$now_time}')";
    }
  }

  // 需要结束的活动记录
  foreach ($existed_rec as $rec) {
    $is_active = false;
    foreach ($current_rec_units as $unit) {
      if ($rec['unit'] == $unit) {
        $is_active = true;
        break;
      }
    }
    if (! $is_active) {
      $number              = $rec['number'];
      $need_to_end_units[] = $rec['unit'];
      $need_to_end[]       = "UPDATE `2kt_activity_history` SET `endTime` = '{$now_time}' WHERE `number` = {$number}";
    }
  }

  $results_add = [];
  $results_end = [];

  if (count($need_to_add) > 0) {
    $results_add = exec_sql_array($need_to_add);
  }

  if (count($need_to_end) > 0) {
    $results_end = exec_sql_array($need_to_end);
  }

  $result_add = ! in_array(false, $results_add, true);
  $result_end = ! in_array(false, $results_end, true);

  $output = [
    'unitAdded' => $need_to_add_units,
    'unitEnded' => $need_to_end_units,
    'statusAdd' => $result_add,
    'statusEnd' => $result_end,
    'sqlAdd'    => $result_add ? '' : $need_to_add,
    'sqlEnd'    => $result_end ? '' : $need_to_end,
  ];

  return $output;

}
